package event

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strings"
)

var WxIgnoreKey map[string]struct{}

func init() {
	WxIgnoreKey = map[string]struct{}{
		"msgType": {},
		"signatureId":{},
		"sendType":{},
		"appName":{},
		"order":{},
		"url":{},
	}
}
type Event struct {
}
func NewEvent() Event{
	return Event{}
}
type EventMap []map[string]interface{}
type EventMapString map[string]string
func (e Event) GetContentBySceneId(sceneId int64) (EventMap,error)  {
	jn := `[
    {
        "msgType":"2",
        "signatureId":"HOME-10002",
        "title":"测试",
        "msg":"22222",
        "url":"",
        "order":"2",
        "sendType":"1"
    },
    {
        "msgType":"3",
        "signatureId":"xiaoyusan",
        "msg":"11111",
        "isSale":"0",
        "order":"1",
        "sendType":"1" 
    },
    {
        "msgType":"1",
        "signatureId":"365",
        "sendType":"1",
        "appName":"xiaoyusan",
        "order":"2",
        "url":"http://baidu.com",
        "first":"22222",
        "first_color":"",
        "keyword1":"k1",
        "keyword1_color":"k1c",
        "keyword2":"k2",
        "keyword2_color":"k2c",
        "keyword3":"k3",
        "keyword3_color":"k3c",
        "remark":"r1",
        "remark_color":"r1c"
    }
]`
	var event EventMap
	err := json.Unmarshal([]byte(jn),&event)
	return event,err
}
func (e Event) TransferMapStringString(eventMap EventMap) ([]map[string]string,error) {
	newData := make([]map[string]string,0)
	for _,val :=range eventMap{
		tmp,err := e.parseEventMapStringString("",val)
		if err != nil {
			return nil,err
		}
		newData = append(newData,tmp)
	}
	return newData,nil
}
func (e Event) parseEventMapStringString(key string,data map[string]interface{}) (map[string]string,error){
	temp := make(map[string]string)
	for k,val := range data {

		newKey := k
		if key != ""{
			newKey = fmt.Sprintf("%s.%s",key,k)
		}
		switch val.(type) {
		case string:
			temp[newKey] = val.(string)
		case map[string]interface{}:
			temp2,err := e.parseEventMapStringString(newKey,val.(map[string]interface{}))
			if err != nil {
				return nil,err
			}
			for k2,val2 := range temp2 {
				temp[k2] = val2
			}
		case []interface{}:
			arr ,_ := val.([]interface{})
			arrStrings := make([]string,0,len(arr))
			for _,v := range arr {
				arrStrings = append(arrStrings,v.(string))
			}
			arrString := strings.Join(arrStrings , ",")
			temp[newKey] = arrString
			
		default:
			retType := reflect.TypeOf(val)
			return nil, fmt.Errorf("Event parse error(%+v),undefine type: %s",val,retType.String())
		}
	}
	return temp,nil
}
func (e Event) GetWxTemplateId(id string) (string,error){
	return "tmplateidxxssss",nil
}
func (e Event) GetWxTemplateKeyVal(data map[string]string) map[string]string {
	newData := make(map[string]string,0)
	for key,val := range data {
		if _,ok := WxIgnoreKey[key]; ok {
			continue
		}
		newData[key] = val
	}
	return newData
}
